<template>
	<view>
		<view class="background"></view>
		<view class="entirety">
		<form @submit="onSubmit">
			<view class="mode">
				<text>维修方式</text>
				<view class="radio">
					<radio-group @change="getRadio">
						<label>
							<radio checked value="arriveStore"/><text>到店维修</text>
						</label>
						<label style="margin-left: 50rpx;">
							<radio value="takeCar"/><text>上门取车</text>
						</label>
					</radio-group>
				</view>
			</view>
		<!-- 客户信息区域 -->	
			<view class="Info">
				<view class="title">
					客户信息
				</view>
				<view class="body">
					<view class="">
						<view>
							车主姓名
						</view>
							<input name="name" placeholder="请输入车主姓名" type="text" />
					</view>
					<view class="">
						<view>
							联系方式
						</view>
						<input name="phone" placeholder="请输入联系方式" type="text" />
					</view>
					<view class="">
						<view>
							预约时间
						</view>
						<view class="time-input-wrapper">
							<picker 
								mode="multiSelector" 
								:range="[dateList, availableTimeList]"
								:value="[dateIndex, timeIndex]"
								@change="bindMultiPickerChange"
								@columnchange="bindMultiPickerColumnChange"
								class="date-picker"
							>
								<input 
									name="date" 
									:value="formatDisplayDateTime()" 
									placeholder="请选择预约时间" 
									disabled 
									class="time-input"
								/>
							</picker>
						</view>
					</view>
					<view v-if="!isMode">
						<view>
							取车位置
						</view>
						<input 
							name="date" 
							:value="locationAddress" 
							placeholder="请选择取车位置" 
							@tap="openLocationPicker"
							disabled
						/>
					</view>
				</view>
			</view>
		<!-- 车辆信息区域 -->	
			<view class="Info">
				<view class="title">
					车辆信息
				</view>
				<view class="body">
					<view>
						<view>
							车辆类型
						</view>
						<view class="select">
							<uni-data-select
							class="uni-data-select"
								 :borderRadius="true"
								 :border="true"
							      v-model="value"
							      :localdata="range"
							      @change="change"
							    />
						</view>
					</view>	
					<view class="">
						<view>
							车牌号
						</view>
						<input name="carCode" placeholder="请输入车牌号" type="text" />
					</view>
				</view>
			</view>
		<!-- 照片区域 -->		
			<view class="pictureInfo">
				<view class="title">
					照片
				</view>
				<view class="body">
					<view>
						整车照片：
						<uni-file-picker
							style="margin-left:55rpx;"
							class="carPicture"
							:value="carImages"
							limit="1"
							@select="onSelectCar"
							@delete="onDeleteCar"
							file-mediatype="image"
						></uni-file-picker>
					</view>
					<view>
						维修部位照片：
						<uni-file-picker
							class="carPicture"
							:value="repairImages" 
							limit="1"
							@select="onSelectRepair"
							@delete="onDeleteRepair"
							file-mediatype="image"
						></uni-file-picker>
					</view>
				</view>
			</view>
		<!-- 提交按钮 -->	
			<view class="btn">
				<button form-type="submit">提交</button>
			</view>
		</form>		
		</view>
	</view>
</template>

<script>
import amap from '@/utils/amap.js'

export default {
	data() {
		return {
			value: 0,
			range: [
				{ value: 0, text: "请选择" }
			],
			isMode: true,
			dateList: [], // 可选日期列表
			timeList: ['09:00', '10:00', '11:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'],
			dateIndex: 0,
			timeIndex: 0,
			selectedDateTime: null,
			availableTimeList: [], // 当天可选时间列表
			carImages: [],
			repairImages: [],
			uploadUrl: 'your_upload_url', // 替换为实际的上传地址
			disabledDates: [], // 存储不可选的日期
			locationAddress: '', // 位置文字描述
			locationInfo: {
				latitude: 0,
				longitude: 0
			}
		}
	},
	mounted() {
		this.initDateTimeList()
		// 加载车辆类型
		this.$request({
			url: 'shop/brand/list',
			method: 'GET',
			header: {
				'Content-Type': 'application/json'
			},
			data: {
				pageNum: 1,
				pageSize: 9999
			},
			success: (res) => {
				if (res.data.code === 200) {
					// 转换数据格式并添加默认选项
					this.range = [
						{ value: 0, text: "请选择" },
						...res.data.rows.map(item => ({
							value: item.id,
							text: item.name
						}))
					];
					
					// 默认选中"请选择"
					this.value = 0;
				} else {
					uni.showToast({
						title: res.data.msg || '获取车辆类型失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				console.error('加载车辆类型失败:', err);
				uni.showToast({
					title: '加载车辆类型失败',
					icon: 'none'
				});
				
				// 加载失败时使用默认数据
				this.range = [
					{ value: 0, text: "请选择" },
					{ value: 1, text: "大客车" },
					{ value: 2, text: "小货车" },
					{ value: 3, text: "小轿车" }
				];
				this.value = 0;
			}
		})
	},
	methods: {
		change(e) {
			console.log("e:", e);
		},
		async onSubmit(e) {
			const formData = e.detail.value
			
			// 表单验证
			if (!formData.name.trim()) {
				uni.showToast({
					title: '请输入车主姓名',
					icon: 'none'
				})
				return
			}
			
			if (!formData.phone.trim()) {
				uni.showToast({
					title: '请输入联系方式',
					icon: 'none'
				})
				return
			}
			
			// 验证手机号格式
			if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				})
				return
			}

			// 验证车辆类型
			if (this.value === 0) {
				uni.showToast({
					title: '请选择车辆类型',
					icon: 'none'
				})
				return
			}

			// 验证车牌号
			if (!formData.carCode.trim()) {
				uni.showToast({
					title: '请输入车牌号',
					icon: 'none'
				})
				return
			}

			// 验证时间是否已选择
			if (!this.selectedDateTime) {
				uni.showToast({
					title: '请选择预约时间',
					icon: 'none'
				})
				return
			}

			// 如果是上门取车，验证取车位置
			if (!this.isMode && !this.locationAddress) {
				uni.showToast({
					title: '请选择取车位置',
					icon: 'none'
				})
				return
			}

			try {
				// 并发上传所有图片
				const uploadTasks = []
				
				// 添加整车照片上传任务
				if (this.carImages.length > 0) {
					uploadTasks.push(
						this.uploadFile(this.carImages[0].url)
							.then(url => ({ type: 'vehicle', url }))
					)
				}
				
				// 添加维修部位照片上传任务
				if (this.repairImages.length > 0) {
					uploadTasks.push(
						this.uploadFile(this.repairImages[0].url)
							.then(url => ({ type: 'repair', url }))
					)
				}

				// 等待所有图片上传完成
				const uploadResults = await Promise.all(uploadTasks)
				console.log('所有图片上传完成:', uploadResults)

				// 从上传结果中获取URL
				const vehiclePhotos = uploadResults.find(r => r.type === 'vehicle')?.url || ''
				const repairPhotos = uploadResults.find(r => r.type === 'repair')?.url || ''

				// 构建位置信息
				const locationString = this.locationAddress ? 
					`${this.locationAddress}|${this.locationInfo.longitude},${this.locationInfo.latitude}` : 
					'无'

				// 构建提交数据
				const submitData = {
					mid: 1, // 店铺id，需要从路由或其他地方获取
					uid: 102, // 用户id，需要从登录信息获取
					type: this.isMode ? '0' : '1', // 维修方式（0 到店维修 1上门取车）
					name: formData.name,
					phone: formData.phone,
					reservationTime: this.selectedDateTime.value,
					submitTime: this.formatDateTime(new Date()),
					location: locationString,
					carTypeId: this.value, // 直接使用选中的数据库id
					carNum: formData.carCode,
					vehiclePhotos,
					repairPhotos,
					status: '0',
					del: '0'
				}

				console.log('提交的数据:', submitData)

				// 使用封装的请求方法
				this.$request({
					url: 'shop/reservation/reservation',
					method: 'POST',
					data: submitData,
					success: (res) => {
						if (res.data.code === 200) {
							console.log('预约提交成功，返回数据:', res.data)
							
							uni.showToast({
								title: '预约成功',
								icon: 'success'
							})
							
							setTimeout(() => {
								uni.navigateTo({
									url: `/packagesMy/maintenanceRecord/maintenanceRecord?id=${res.data.id}`,
									fail: (err) => {
										console.error('页面跳转失败:', err)
										uni.navigateBack()
									}
								})
							}, 1500)
						} else {
							throw new Error(res.data.msg || '预约失败')
						}
					},
					fail: (err) => {
						console.error('提交失败:', err)
						uni.showToast({
							title: err.message || '提交失败',
							icon: 'none'
						})
					}
				})
			} catch (error) {
				console.error('提交失败:', error)
				uni.showToast({
					title: error.message || '提交失败',
					icon: 'none'
				})
			}
		},
		getRadio(e){
			console.log(e.detail.value)
			if(e.detail.value == "takeCar"){
				this.isMode = false
			}else{
				this.isMode = true
			}
		},
		initDateTimeList() {
			const now = new Date()
			const dateList = []
			
			// 生成未来15天的日期列表
			for (let i = 0; i < 15; i++) {
				const date = new Date(now)
				date.setDate(date.getDate() + i)
				let displayText = this.formatDateDisplay(date, i)
				dateList.push(displayText)
			}
			
			this.dateList = dateList
			this.updateAvailableTime() // 初始化可选时间
		},
		formatDateDisplay(date, index) {
			const month = (date.getMonth() + 1).toString().padStart(2, '0')
			const day = date.getDate().toString().padStart(2, '0')
			const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]
			
			// 前三天显示特殊标记
			let prefix = ''
			if (index === 0) prefix = '今天'
			else if (index === 1) prefix = '明天'
			else if (index === 2) prefix = '后天'
			
			return prefix ? `${prefix}(${month}月${day}日 ${weekDay})` : `${month}月${day}日 ${weekDay}`
		},
		updateAvailableTime() {
			const now = new Date()
			const currentHour = now.getHours()
			const currentMinute = now.getMinutes()
			
			// 如果是当天，需要过滤已过时间
			if (this.dateIndex === 0) {
				this.availableTimeList = this.timeList.filter(time => {
					const [hour, minute] = time.split(':').map(Number)
					// 只显示未来的时间点（预留30分钟缓冲）
					return hour > currentHour || (hour === currentHour && minute > currentMinute + 30)
				})
				
				// 如果当天没有可选时间，自动切换到明天
				if (this.availableTimeList.length === 0) {
					this.dateIndex = 1
					this.availableTimeList = [...this.timeList]
				}
				
				// 重置时间索引
				this.timeIndex = 0
			} else {
				// 非当天显示所有时间
				this.availableTimeList = [...this.timeList]
			}
		},
		bindMultiPickerChange(e) {
			const [dateIndex, timeIndex] = e.detail.value
			this.dateIndex = dateIndex
			this.timeIndex = timeIndex
			
			// 更新选中的日期时间
			const now = new Date()
			const selectedDate = new Date(now)
			selectedDate.setDate(now.getDate() + dateIndex)
			
			const [hours, minutes] = this.availableTimeList[timeIndex].split(':')
			selectedDate.setHours(parseInt(hours))
			selectedDate.setMinutes(parseInt(minutes))
			selectedDate.setSeconds(0)
			
			this.selectedDateTime = {
				display: `${this.dateList[dateIndex]} ${this.availableTimeList[timeIndex]}`,
				value: this.formatDateTime(selectedDate)
			}
		},
		bindMultiPickerColumnChange(e) {
			const { column, value } = e.detail
			if (column === 0) {
				this.dateIndex = value
				this.updateAvailableTime()
			} else {
				this.timeIndex = value
			}
		},
		formatDisplayDateTime() {
			if (!this.selectedDateTime) return ''
			return this.selectedDateTime.display
		},
		formatDateTime(date) {
			const year = date.getFullYear()
			const month = (date.getMonth() + 1).toString().padStart(2, '0')
			const day = date.getDate().toString().padStart(2, '0')
			const hours = date.getHours().toString().padStart(2, '0')
			const minutes = date.getMinutes().toString().padStart(2, '0')
			const seconds = date.getSeconds().toString().padStart(2, '0')
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
		},
		// 检查日期是否可选
		isDateDisabled(date) {
			return this.disabledDates.includes(this.formatDate(date));
		},

		// 整车照片选择
		onSelectCar(e) {
			if (e.tempFiles && e.tempFiles.length > 0) {
				this.carImages = [{
					url: e.tempFiles[0].path,
					name: e.tempFiles[0].name,
					type: 'image'
				}]
			}
		},

		// 维修部位照片选择
		onSelectRepair(e) {
			if (e.tempFiles && e.tempFiles.length > 0) {
				this.repairImages = [{
					url: e.tempFiles[0].path,
					name: e.tempFiles[0].name,
					type: 'image'
				}]
			}
		},

		// 删除整车照片
		onDeleteCar() {
			this.carImages = [];
		},

		// 删除维修部位照片
		onDeleteRepair(e) {
			const index = e.index;
			this.repairImages.splice(index, 1);
		},

		// 文件上传方法
		uploadFile(filePath) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: this.$fileBaseUrl + '/upload', // 使用配置的文件上传基础URL
					filePath: filePath,
					name: 'file',
				
					success: (res) => {
						try {
							const data = JSON.parse(res.data)
							if (data.code === 200) {
								console.log('上传成功，返回数据:', data)
								resolve(data.data.url)
							} else {
								console.error('上传失败:', data.msg)
								reject(new Error(data.msg))
							}
						} catch (error) {
							console.error('解析上传响应失败:', error)
							reject(error)
						}
					},
					fail: (err) => {
						console.error('上传失败:', err)
						reject(err)
					}
				})
			})
		},
		// 打开位置选择器
		openLocationPicker() {
			uni.chooseLocation({
				success: async (res) => {
					console.log('选择位置成功:', res)
					
					try {
						// 使用高德地图进行地址解析
						const location = {
							latitude: res.latitude,
							longitude: res.longitude
						}
						
						const geoResult = await amap.reverseGeocoder(location)
						
						// 将位置信息格式化为字符串: "地址详情|经度,纬度"
						this.locationAddress = res.address
						this.locationInfo = {
							latitude: res.latitude,
							longitude: res.longitude
						}
						
						// 格式化位置字符串
						const locationString = `${res.address}|${res.longitude},${res.latitude}`
						
						console.log('地址解析结果:', geoResult)
						console.log('格式化的位置字符串:', locationString)
						
					} catch (error) {
						console.error('地址解析失败:', error)
						// 如果地址解析失败，仍然保存格式化的位置信息
						const locationString = `${res.address}|${res.longitude},${res.latitude}`
						this.locationAddress = res.address
						this.locationInfo = {
							latitude: res.latitude,
							longitude: res.longitude
						}
					}
				},
				fail: (err) => {
					console.error('选择位置失败:', err)
					uni.showToast({
						title: '选择位置失败',
						icon: 'none'
					})
				}
			})
		},
	}
}
</script>

<style>
	page{
		background-color: #f0f0f0;
		padding: 0 20rpx;
	}
	.background {
		width: 750rpx;
		height: 280rpx;
		background-color: #2979ff;
		margin-left: -20rpx;
	}
	.entirety{
		position: absolute;
		top: 20rpx;
	}
// 维修方式区域样式
	.mode{
		width: 670rpx;
		height: 100rpx;
		line-height: 100rpx;
		background-color: white;
		padding: 0rpx 20rpx;
		border-radius: 20rpx;
		display: flex;
		position: relative;
	}
	.mode > text{
		font-size: 32rpx;
	}
	.radio {
		transform: scale(0.5);
		font-size: 50rpx;
		position: absolute;
		right: -120rpx;
		/* border: 2rpx solid red; */
	}
// 客户|车辆信息区域样式
	.Info{
		padding: 20rpx 20rpx;
		width: 670rpx;
		background-color: white;
		border-radius: 20rpx;
		margin-top: 20rpx;
	}
	.Info > .title{
		font-size: 32rpx;
		border-bottom: 6rpx solid #f0f0f0;
		height: 70rpx;
		line-height: 70rpx;
	}
	.Info > .body {
		padding: 10rpx 0;
	}
	.Info > .body > view {
		display: flex;
		margin-top: 30rpx;
	}
	.Info > .body > view > view:nth-child(1) {
		background-color: #4FA2FF;
		color: white;
		font-size: 28rpx;
		border-radius: 40rpx;
		height: 60rpx;
		line-height: 60rpx;
		width: 150rpx;
		text-align: center;
		
	}
	.Info > .body > view > input{
		border: 2rpx solid #c7c7c7;
		border-radius: 40rpx;
		height: 60rpx;
		line-height: 60rpx;
		margin-left: 20rpx;
		padding-left: 30rpx;
		width: 500rpx;
		font-size: 28rpx;
	}
	.uni-input-placeholder{
		color: #c7c7c7;
	}
	.carCategory{
		border: 2rpx solid red;
		margin-left: 30rpx;
	}
	.select{
		margin-left: 20rpx;
		width: 500rpx;
	}
// 照片区域样式
	.pictureInfo{
		padding: 20rpx 20rpx;
		width: 670rpx;
		background-color: white;
		border-radius: 20rpx;
		margin-top: 20rpx;
	}
	.pictureInfo > .title{
		font-size: 32rpx;
		border-bottom: 6rpx solid #f0f0f0;
		height: 70rpx;
		line-height: 70rpx;
	}
	.pictureInfo > .body{
		margin-bottom: 10rpx;
	}
	.pictureInfo > .body > view {
		display: flex;
		margin-top: 30rpx;
	}
// 提交按钮样式
	.btn{
		margin-top: 70rpx;
		margin-bottom: 140rpx;
	}
	.btn > button{
		width: 500rpx;
		background-color: #2979ff;
		color: white;
		border-radius: 40rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 30rpx;
		
	}
	.carPicture {
		flex: 1;
	}

	/* 时间选择器样式 */
	.time-input-wrapper {
		position: relative;
		width: 490rpx; /* 减小输入框宽度 */
		margin-left: 20rpx;
	}

	.time-input {
		border: 2rpx solid #c7c7c7;
		border-radius: 40rpx;
		height: 60rpx;
		line-height: 60rpx;
		padding: 0 30rpx;
		width: 100%;
		font-size: 28rpx;
		background-color: #fff;
		box-sizing: border-box;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	/* 选择器弹出层样式 */
	.uni-picker-view-column {
		text-align: center;
		line-height: 80rpx;
	}

	.uni-picker-view-column view {
		color: #333;
	}

	.uni-picker-view-column view.selected {
		color: #2979ff;
		font-weight: bold;
	}

	/* 输入框占位符样式 */
	.time-input::placeholder {
		color: #c7c7c7;
	}

	/* 选中状态的输入框样式 */
	.time-input[disabled] {
		background-color: #fff;
		color: #333;
	}
</style>
